<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>新建单据</title>
   <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <link rel="stylesheet" href="../css/base.css">
  <link rel="stylesheet" href="../../css/element-ui.css" />
  <link rel="stylesheet" href="../css/index.css">
  	<script src="../../js/common/jquery.min.js"></script>
   <script src="../../js/common/browser.min.js"></script>
    <script src="../../js/common/vue.js"></script>
    <script src="../../js/common/element-ui.js"></script>
    <script src="../js/common/common.js"></script>
</head>
<body>
<div id="wtNewly">
<div  class="container">
  <div class="rj-header">
    <p class="nav">
      <span class="default">您现在所在的位置:</span>
      <span class="direction">{{prams.breadcrumb}}</span>
    </p>
    <div class="search-container">
    <div class="item">
        <label>单据流水号</label>
        <input type="text" class="forbid" disabled="disabled" :value="Head.BillSN" />
      </div>
      <div class="item">
        <label>录入人</label>
        <input type="text" class="forbid"  disabled="disabled" :value="Head.InputUserName"/>
      </div>
      <div class="item">
        <label>录入时间</label>
        <div class="time-wrapper">
	        <el-date-picker
	        	class="forbid"
	        	:disabled="forbid"
				v-model="Head.InputTime"
				type="datetime"
				format="yyyy-MM-dd HH:mm:ss"
				>
			</el-date-picker>
        </div>
      </div>
      <div class="item">
        <label>领用房间</label>
        <select v-model="selectedRoom" :disabled ="isSaved">
        	<option  value ="all">全部</option>
         	<option v-for="v in inRooms" :value ="v.RoomID">{{v.RoomName}}</option>
        </select>
      </div>
      <div class="item">
        <label>发送人</label>
        <input type="text" class="forbid" disabled="disabled" :value="Head.SendUserName"/>
      </div>
       <div class="item">
        <label>审核人</label>
        <input type="text" class="forbid" disabled="disabled" :value="Head.AuditUserName"/>
      </div>
      <div class="item">
        <label>领用人</label>
        <input type="text" id="lyman" :class="{forbid:Head.StatusStr !== 'sh'}" :autofocus="Head.StatusStr == 'sh'" :disabled = "Head.StatusStr !== 'sh'" v-model="Head.DrawUserName"/>
      </div>
      <div class="item">
        <label>出库科室</label>
        <input type="text" class="forbid" disabled="disabled" :value="Head.OutDeptName"/>
      </div>
      <div class="item">
        <label>备注</label>
        <textarea type="text"  rows="1" v-model="Head.Comment" :disabled ="isSaved"/></textarea>
      </div>
      <div class="item">
        <label>单据状态</label>
        <input type="text" class="forbid" disabled="disabled" :value="StatusName" />
      </div>
    </div>
  </div>
  <div class="btn-group">
  <span v-if="!isUserJS">
   	<el-button type="success" v-if="!isSaved" @click="handle">保存</el-button>
  	<el-button type="success" v-else @click="editor" :disabled = "!operations.isEditor">修改</el-button>
  	<el-button type="info"  :disabled = "!operations.isSend" @click="send">提交申请</el-button>
  </span>
 <span v-else>
 	<el-button type="success"  @click="commit" :disabled = "!operations.isSh">审核</el-button>
 	<el-button type="success"  @click="revoke" :disabled = "Head.StatusStr !== 'sh'">撤销审核</el-button>
 	<el-button type="success"  @click="receive" :disabled = "operations.isSh">完成</el-button>
 </span>
  
  <el-button type="info" @click="back">返回</el-button> 
</div>
  <div class="table-wrapper"> 
  	 <table class="bill-table">
            	<tr style="background-color: #ddd;">
                 	<th v-for="(data,index) in tableData"><p>{{data}}</p></th>
                  	<th><p>操作</p></th>
                </tr>
                <tr :class="{active:active==index}" v-if="BillData.length"  v-for="(v,index) in BillData"   > <!-- @click="check(index,v.BillSN)"  @dblclick="href(v.BillSN)" -->
                    <td><p>{{v.GoodsCode}}</p></td>
                    <td><p>{{v.GoodsName}}</p></td>
                    <td><p>{{v.GoodsSpec}}</p></td>
                    <td><p>{{v.BoxUnit}}</p></td>
                    <td><p><input type="number" class="setInput" v-model="v.ApplyNum" :disabled ="isSaved"/></p></td>
                    <!-- -<td><p>{{v.GoodsCount}}</p></td>- -->
                    <td><p>{{v.RefPrice}}</p></td>
                    <td><p>{{v.consultMoney}}</p></td>
                    <td><p><input class="setInput" v-model="v.Comment" :disabled ="isSaved"/></p></td>
                   <!-- - <td><p>{{v.CardNumberList}}</p></td>
                    <td><p>{{v.ChargeCode}}</p></td>- -->
                    <td><p><input type="number" class="setInput" v-model="v.ActualSendNum" :disabled ="!isEditorActualSendNum"/></p></td>
                    <td><p><el-button type="primary" size="mini" @click="del(v,index)" :disabled ="isSaved">删除</el-button></p></td>
                </tr>
                 <tr v-show="!isSaved">
                 	<td v-for="(data,index) in tableHeard"><p><input type="text"  autofocus @keyup.enter="popup" style="height: 26px;width: 90%;text-indent: 1em;border: none;" v-if="index == 0"/></p></th>
                </tr>
      </table>
  </div>
	
</div>
</div>
<script>
var app = new Vue({
	  el: '#wtNewly',
	  data: {
		  prams:JSON.parse(GetRequest().param),
		  userJS:JSON.parse(localStorage.getItem("userJS")),
		  isUserJS:localStorage.getItem("userJS")&&JSON.parse(localStorage.getItem("userJS")).length>0?true:false,
		  BillSN:GetRequest().BillSN?JSON.parse(GetRequest().BillSN):null,
		  forbid:true,
		  userID:JSON.parse(localStorage.getItem('currentUser')).Ygid,
		  inputTimeStart:'',
		  inputTimeEnd:'',
		  saveOrUpdate:"save",
		  isSaved:false,
		  isDisabled:true,
		  tableData:['物品代码','物品名称','规格型号','计量单位','申请数','参考单价','参考金额','备注','实发数'],
		  tableHeard:new Array(10),	
		  BillData:[],
		  active:0,
		  inRooms:[],
		  selectedRoom:"all",
		  Head:{
			  	"BillSN": "",
			  	"BillType": null,
				"BillTypeStr":"ly",
				"InputUserName": JSON.parse(localStorage.getItem('currentUser')).Xm,
				"AdditionalReason": null,
				"AdditionalReasonTypeStr":"",
				"OutDeptAccountID": JSON.parse(localStorage.getItem('deptAccount')).DeptAccountID,
				"OutDeptAccountName": JSON.parse(localStorage.getItem('deptAccount')).DeptAccountName,
				"InputTime": "",
				"OutDeptCode": JSON.parse(localStorage.getItem('deptInfo')).Ksdm,
				"OutDeptName":JSON.parse(localStorage.getItem('deptInfo')).Ksmc,
				"AuditUserName":"",
				"InRoomID": "",
				"InRoomName": "",
				"InRoomCode": "",
				"GoodsBookID": "",
				"InputUserID":"",
				"AuditUserID":"",
				"DrawUserName":"",
				"DrawUserID":"",
				"SendUserName":"",
				"SendUserID":"",
				"SendTime":"",
				"InputTime": "",
				"AuditTime": "",
			    "DrawTime":"",
			    "Comment":"",
				"StatusStr": null,
				"PrintTimes":"",
				"HelpNumber":""
		},
		 Detail : {
				"BillDetailSN": "",
				"BillSN": "",
				"GoodsID": "",
				"ApplyNum": 0,
				"ActualSendNum": "",
				"RefPrice":"",
			  	"ChargeCodeID":"",
				"Sort": 0,
				"Comment": ""
			},
		  newBillData:[],
	  },
	 created:function(){
		 console.log(this.prams)
		 var that = this;
		 this.getInRoom().then(function(){
			 if(that.BillSN){
				 that.isSaved = !that.isSaved
				 that.getBills(that.BillSN)
			 }
		 })
	 },
	 computed:{
		 StatusName:function(){
// 			 if(this.Head.StatusStr == 'sh'){
// 				 document.getElementById('lyman').focus()
// 			 }
			 return this.toName(this.Head.StatusStr)
		 },
		 operations:function(){
			 return this.operationRights(this.Head.StatusStr)
		 },
		 isAudit:function(){
			 return this.Head.StatusStr&&this.Head.StatusStr=="lr"
		 },
		 isChecked:function(){
			 return this.Head.StatusStr&&this.Head.StatusStr=="fs"
		 },
		 isEditorActualSendNum:function(){
			 if(this.isUserJS){
				 if(this.Head.StatusStr == 'fs'){
					 return true
				 }
			 }
			 return false
		 }
	 },
	 watch:{
		 		selectRoomName:function(curVal,oldVal){
						this.$set(this.Head,"RoomInfo",curVal)
		　　　　　　　　},
				selectedRoom:function(curVal,oldVal){
					var that = this
					for(var i=0;i<this.inRooms.length;i++){
						 if(curVal == that.inRooms[i].RoomID){
							that.Head.InRoomID=that.inRooms[i].RoomID;
							that.Head.InRoomCode=that.inRooms[i].RoomCode;
							that.Head.InRoomName=that.inRooms[i].RoomName
						 }
					 }
					console.log(that.Head)
	　　　　　　　　},
		      BillData:{
				　　　　handler(newValue, oldValue) {
						newValue.forEach(function(item){
							item.consultMoney = Number(item.ApplyNum*item.RefPrice).toFixed(2)
			 	 		})
				　　　　},
				　　　　deep: true
				　　} ,
	　　　　　　　 
			 
	　　　　　　},
	 methods:{
		 operationRights: function (value) {
				if (!value) return ''
					value = value.toString()
				var operations={}
					switch(value)
					{
						case "lr": 
							operations={
								isEditor:true,
								isSend:true,
								isSh:false,
								isLy:false,
								isZf:true
							}
							break;
						
						case "fs": 
							operations={
								isEditor:true,
								isSend:false,
								isSh:true,
								isLy:false,
								isZf:true
							}
							break;
						case "sh":
							operations={
								isEditor:false,
								isSend:false,
								isSh:false,
								isLy:true,
								isZf:false
							}
						case "ly":
							operations={
								isEditor:false,
								isSend:false,
								isSh:false,
								isLy:false,
								isZf:false
							}
						case "zf": 
							operations={
								isEditor:false,
								isSend:false,
								isSh:false,
								isLy:false,
								isZf:false
							}
					   	 	break;
						default:
							operations={
								isEditor:true,
								isSend:false,
								isSh:false,
								isLy:false,
								isZf:false
							}	
						}
					return operations
			},	  
		 toName: function (value) {
			    if (!value) return ''
			    value = value.toString()
			    var StatusName = null;
			    switch(value)
				{
					case "lr": 
							StatusName ="录入"
				 		 break;
					case "fs": StatusName ="发送"
					  	break;
					case "sh": StatusName ="审核"
				  		break;
					case "ly": StatusName ="完成"
				  		break;
					case "dz": StatusName ="登账"
					  	break;
					case "jz": StatusName ="结账"
					  	break;
					case "zf": StatusName ="作废"
					  	break;
				}
			    return StatusName
			  },
		setToEqual:function(obj1,obj2){
			if(!obj1||!obj2) return;
			var keys1 = Object.keys(obj1);
			var keys2 = Object.keys(obj2);
			for(var i=0;i<keys1.length;i++){
				for(var j=0;j<keys2.length;j++){
					if(keys1[i]==keys2[j]){
						obj1[keys1[i]] = obj2[keys2[j]];
						break;
					}
				}
			}
		},
		update:function(){
			var that = this
			 for(var i = 0,len=this.BillData.length;i<len;i++){
					if(!/^[0-9]+$/.test(this.BillData[i].ApplyNum||this.BillData[i].ApplyNum<= 0)){
						that.$message.error('申请数应为大于0的整数！');
						return false
					}
					 
				}
			 var obj={};
			 obj.Head = {
					 "BillSN":this.Head.BillSN,
					 "BillType":this.Head.BillType,
					 "BillTypeStr":this.Head.BillTypeStr,
					 "AdditionalReasonType":this.Head.AdditionalReasonType,
					 "AdditionalReasonTypeStr":this.Head.AdditionalReasonTypeStr,
					 "OutDeptAccountID":this.Head.OutDeptAccountID,
					 "OutDeptCode":this.Head.OutDeptCode,
					 "InRoomID":this.Head.InRoomID,
					 "InRoomCode":this.Head.InRoomCode,
					 "GoodsBookID":this.Head.GoodsBookID,
					 "InputUserID":this.Head.InputUserID,
					 "AuditUserID":this.Head.AuditUserID,
					 "DrawUserID":this.Head.DrawUserID,
					 "SendUserName":this.Head.SendUserName,
						"SendUserID":this.Head.SendUserID,
						"SendTime":this.Head.SendTime,
					 "InputTime":this.Head.InputTime,
					 "AuditTime":this.Head.AuditTime,
					 "DrawTime":this.Head.DrawTime,
					 "Comment":this.Head.Comment,
					 "Status":this.Head.Status,
					 "StatusStr":this.Head.StatusStr,
					 "PrintTimes":this.Head.PrintTimes,
					 "HelpNumber":this.Head.HelpNumber
			 } 
			 obj.Details=this.BillData
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'ModifyDrawBill',
				        drawBill:JSON.stringify(obj),
				        userID: this.userID
					  } 
			 this._fetch(parms).then(function(){
				 that.getBills(that.Head.BillSN).then(function(){
					 that.isSaved = !that.isSaved
					 that.isDisabled = !that.isDisabled
					 that.$message({
				          message: '修改成功',
				          type: 'success'
				        });
				 })
				
				 
			 })
			 
		},
		 editor:function(){
			 var that = this
			 that.isSaved = !that.isSaved
			 this.saveOrUpdate = "update"
			
		 },
		 handle:function(){
			switch(this.saveOrUpdate)
			{
				case "save":
				  	this.save();
				  break;
				case "update":
					this.update();
				  break;
			}
		 },
		 getBills:function(billSN){
				var that = this
			 	var parms ={
						className: 'TwoLevelStockManager',
				        method: 'GetBill',
				        billSN:billSN
					  } 
			 return	this._fetch(parms).then(function(data){
					 that.setToEqual(that.Head,data.Head)
					 that.BillData = data.Details
					 that.selectedRoom = data.Head.InRoomID;
					 //for(var i=0;i<that.inRooms.length;i++){
						// if(that.inRooms[i].InRoomID ==data.Head.InRoomID){
						//	 that.selectedRoom = that.inRooms[i]
						// }
					// }
				 });
		 },
		 save:function(){
			 var that = this
			 if(this.BillData.length == 0){
				 that.$message.error('请新建领用单');
				return false
			 }
			 if(this.selectedRoom == "all"){
				 that.$message.error('请选择房间号');
					return false
			 }
			for(var i = 0,len=this.BillData.length;i<len;i++){
				if(!/^[0-9]+$/.test(this.BillData[i].ApplyNum||this.BillData[i].ApplyNum<= 0)){
					that.$message.error('申请数应为大于0的整数！');
					return false
				}
				 
			}
			var obj = {}
			var Head = {
					"BillTypeStr":this.Head.BillTypeStr,
					"AdditionalReasonTypeStr":this.Head.AdditionalReasonTypeStr,//空 
					"OutDeptAccountID": this.Head.OutDeptAccountID,
					"OutDeptCode":this.Head.OutDeptCode,
					"InRoomID": this.Head.InRoomID,
					"InRoomCode":this.Head.InRoomCode,
					"GoodsBookID":this.Head.GoodsBookID,
					"InputUserID":this.Head.InputUserID,
					"AuditUserID":this.Head.AuditUserID,//空
					"DrawUserID":this.Head.DrawUserID,//空
					
					"SendUserName":this.Head.SendUserName,
					"SendUserID":this.Head.SendUserID,
					"SendTime":this.Head.SendTime,
					
					"InputTime": this.Head.InputTime,//空
					"AuditTime":this.Head.AuditTime,
				    "DrawTime":this.Head.DrawTime,//空
				    "Comment":this.Head.Comment,
					"StatusStr":this.Head.StatusStr,
					"PrintTimes":this.Head.PrintTimes,//空
					"HelpNumber":this.Head.HelpNumber
			}
			var Details = [];
			this.BillData.forEach(function(item,index){
				var Detail = {
						"BillDetailSN":"",
						"BillSN": "",
						"GoodsID":item.GoodsID,
						"ApplyNum": item.ApplyNum,
						"ActualSendNum": item.ActualSendNum,
						"RefPrice": item.RefPrice,
					  	"ChargeCodeID":item.ChargeCodeID,
						"Sort": index+1,
						"Comment": item.Comment
				}
				Details.push(Detail)
			})
			obj.Head =Head
			obj.Details =Details
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'InputDrawBill',
				        drawBill:JSON.stringify(obj),
				        userID: this.userID
					  } 
			 this._fetch(parms).then(function(data){
				 that.getBills(data).then(function(){
					 that.isSaved = !that.isSaved
					 that.isDisabled = !that.isDisabled
					 that.$message({
				          message: '保存成功',
				          type: 'success'
				        });
				 })
				
				 
			 })
			 
		 },
		 send:function(){
			 var that = this;
			 if(this.saveOrUpdate !=="save"){
				 that.$message.error('请先保存');
				 return false;
			 }
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'SendDrawBill',
				        billSN:this.Head.BillSN,
				        userID: this.userID
					  } 
			 this._fetch(parms).then(function(data){
				 that.getBills(that.Head.BillSN).then(function(){
					// that.isSaved = !that.isSaved
					 //that.isDisabled = !that.isDisabled
					 that.$message({
				          message: '发送成功',
				          type: 'success'
				        });
				 })
				 })
		 },
		 commit:function(){
			 var that = this;
			 if(!this.isUserJS){
				 this.$message.error('很抱歉你没有权限审核！');
				 return false
			 }
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'AuditDrawBill',
				        billSN:this.Head.BillSN,
				        details:JSON.stringify(this.BillData),
				        userID: this.userID,
					  } 
			 this._fetch(parms).then(function(data){
				 that.getBills(that.Head.BillSN).then(function(){
						// that.isSaved = !that.isSaved
						 //that.isDisabled = !that.isDisabled
						 that.$message({
					          message: '审核成功',
					          type: 'success'
					        });
					 })
				 })
				
		 },
		 revoke:function(){
			 var that = this;
			 if(!this.isUserJS&&!this.Head.StatusStr !== 'sh'){
				 this.$message.error('很抱歉你没有权限！');
				 return false
			 }
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'UndoAuditDrawBill',
				        billSN:this.Head.BillSN,
				        userID: this.userID
					  } 
			 this._fetch(parms).then(function(data){
				 that.getBills(that.Head.BillSN).then(function(){
						 that.$message({
					          message: '撤销成功',
					          type: 'success'
					        });
					 })
				 })
				
			 
		 },
		 receive:function(){
			 var that = this;
			 if(!this.isUserJS){
				 this.$message.error('很抱歉你没有权限！');
				 return false
			 }
			 if(!this.Head.DrawUserName||this.Head.DrawUserName==""){
				 this.$message.error('请输入领用人工号！');
				 return false
			 }
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'DrawDrawBill',
				        billSN:this.Head.BillSN,
				        userID: this.Head.DrawUserName,
					  } 
			 this._fetch(parms).then(function(data){
				 that.getBills(that.Head.BillSN).then(function(){
						 that.$message({
					          message: '领用成功',
					          type: 'success'
					        });
					 })
				 })
				
			},
		 del:function(v,index){
			 this.BillData.splice(index,1)
		 },
		 back:function(){
			 window.history.back()
		 },
		 popup:function(){
			 var that = this
			 //parent.$('#goodsSelectWrap').show()
			 parent.$('#goodsSelectWrap').load(getRootPath()+'new/view/GoodsQuery.html')
		 },
		 getInRoom: function(){
			 var that = this
			 //var DeptAccountID = this.prams.InDeptAccount.DeptAccountID
			 var DeptAccountID =JSON.parse(localStorage.getItem("deptInfo")).DeptAccountID
			 var Dep = this.conditionModel("a.DeptAccountID", null, "Equal", DeptAccountID, "String")
			 var Status = this.conditionModel("a.Status", null, "Equal", 1, "Int32")
			 var yxbz  = this.conditionModel("a.yxbz ", null, "Equal", 1, "Int32")
			 var arr = [Dep, Status, yxbz] 	
		      var  condition = this.conditionsModel(arr, "AND")
			 var parms ={
						className: 'TwoLevelStockManager',
				        method: 'GetRoomsToDepts',
				        condition:JSON.stringify(condition),
				        userID: this.userID
					  } 
			return this._fetch(parms).then(function(data){
				 if(data.length == 0){
					 that.$message.error('暂无房间可选！');
					 return false
				 }
				 that.inRooms = data
				 //that.selectedRoom = data[0]
				 that.$set(that.Head,"RoomInfo",that.selectedRoom)
			 })
			 
		 },
		conditionModel:function(ColumnName, FullString, Oper, Value, Type) {

		      var obj = {
		          "ColumnName": ColumnName,
		          "FullString": FullString,
		          "Oper": Oper,
		          "Value": Value,
		          "Type": Type
		      }
		      return obj;
		  },
		  conditionsModel:function(Conditions, Type) {
		      var obj = {
		          "Conditions": Conditions,
		          "Type": Type
		      }
		      return obj
		  },
		 _fetch:function(parms){
			 var that = this
			 return new Promise(function(resolve, reject) {
			 $.ajax({
				  type: 'POST',
				  url: getRootPath()+'/api/sendPostRequest' ,
				  headers: {
					  'Accept': 'application/json',
				      'Content-Type': 'application/json'
			        },
				  data: JSON.stringify(parms),
				  success: function(res){
					  if(res.isSessionInvalidated){
						  parent.window.location.href = getRootPath()+'login.html'
					  }
					  if(res.issuccess==0){
						 var result = res.result.match(/^[ ]*$/)?res.result:JSON.parse(res.result);
						 resolve(result)
					  }else {
						  that.$message.error(res.message)
						  reject(res.message);
					  }
				},
				error:function(err){
					new Error(err)
				}
			 });
			 });
		 }
		
	 }
	})
window.addEventListener('message',function(e){
    if(e.source!=window.parent) return;
    var newBillData = e.data
    if(app.BillData.length>0){
        for(var i = 0,len=app.BillData.length;i<len;i++){
        	if(app.BillData[i].GoodsID == newBillData.GoodsID){
    			app.$message.error('新建物品不可重复！');
				 return false
    		}
        }
    }
    newBillData.ApplyNum = newBillData.ApplyNum||0
    newBillData.RefPrice = newBillData.LatestPrice
    newBillData.consultMoney = newBillData.ApplyNum*newBillData.RefPrice
	app.$set(app.Head,"GoodsBookID",newBillData.GoodsBookID)
    app.$set(app.BillData,app.BillData.length,newBillData)
})
	
</script>
</body>
</html>